package cn.wolfcode.web.controller;

import cn.wolfcode.common.domain.UserInfo;
import cn.wolfcode.common.exception.BusinessException;
import cn.wolfcode.common.web.Result;
import cn.wolfcode.common.web.anno.RequireLogin;
import cn.wolfcode.domain.OrderInfo;
import cn.wolfcode.domain.SeckillProductVo;
import cn.wolfcode.mq.MQConstant;
import cn.wolfcode.mq.OrderMessage;
import cn.wolfcode.redis.SeckillRedisKey;
import cn.wolfcode.service.IOrderInfoService;
import cn.wolfcode.service.ISeckillProductService;
import cn.wolfcode.util.UserUtil;
import cn.wolfcode.web.msg.SeckillCodeMsg;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.ConcurrentHashMap;


@RestController
@RequestMapping("/order")
@Slf4j
public class OrderInfoController {
    @Autowired
    private ISeckillProductService seckillProductService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    @Autowired
    private IOrderInfoService orderInfoService;
    public static final ConcurrentHashMap<Long, Boolean> stockOverMap = new ConcurrentHashMap<>();
    @RequireLogin
    @RequestMapping("/doSeckill")
    public Result<String> doSeckill(int time, Long seckillId, HttpServletRequest request){
        //判断参数是否合法
        if(StringUtils.isEmpty(time+"") || StringUtils.isEmpty(seckillId+"")){
            throw new BusinessException(SeckillCodeMsg.PARAM_ERROR);
        }
        //判断本地标识,减少操作redis的次数
        Boolean isOver = stockOverMap.get(seckillId);
        if(isOver != null && isOver){
            throw new BusinessException(SeckillCodeMsg.SECKILL_STOCK_OVER);
        }
        //判断商品是否在秒杀时间内
        SeckillProductVo vo = seckillProductService.find(time, seckillId);
        /*if(!DateUtil.isLegalTime(vo.getStartDate(), time)){
            throw new BusinessException(SeckillCodeMsg.SECKILL_TIME_ERROR);
        }*/
        //获取缓存中当前登录的用户信息
        String token = request.getHeader("token");
        UserInfo user = UserUtil.getUser(redisTemplate, token);
        Boolean flag = redisTemplate.opsForSet().isMember(SeckillRedisKey.SECKILL_ORDER_SET.getRealKey(time + ""),
                user.getPhone() + ":" +seckillId);
        //判断用户是否重复下单
        if(flag != null && flag){
            throw new BusinessException(SeckillCodeMsg.REPEAT_SECKILL);
        }
        //使用redis存商品库存,防止并发访问数据库
        Long stockCount = redisTemplate.opsForHash().increment(SeckillRedisKey.SECKILL_STOCK_COUNT_HASH.getRealKey(time+""),
                seckillId+"", -1L);
        if(stockCount <= 0){
            stockOverMap.put(seckillId, true);
            throw new BusinessException(SeckillCodeMsg.SECKILL_STOCK_OVER);
        }
        //创建消息封装对象
        OrderMessage orderMessage = new OrderMessage();
        orderMessage.setTime(time);
        orderMessage.setSeckillId(seckillId);
        orderMessage.setToken(token);
        orderMessage.setUserPhone(user.getPhone());
        //发送同步消息
        rocketMQTemplate.syncSend(MQConstant.ORDER_PEDDING_TOPIC, orderMessage);
        return Result.success("正在抢购中,请稍后...");
    }

    @RequestMapping("/find")
    public Result<OrderInfo> find(String orderNo, HttpServletRequest request){
        //参数校验
        if(StringUtils.isEmpty(orderNo)){
            throw new BusinessException(SeckillCodeMsg.PARAM_ERROR);
        }
        //判断订单是否存在
        OrderInfo orderInfo = orderInfoService.find(orderNo);
        if(orderInfo == null){
            throw new BusinessException(SeckillCodeMsg.PARAM_ERROR);
        }
        //判断当前查询的订单是否为当前用户自己的订单
        UserInfo user = UserUtil.getUser(redisTemplate, request.getHeader("token"));
        if(!user.getPhone().equals(orderInfo.getUserId())){
            throw new BusinessException(SeckillCodeMsg.PARAM_ERROR);
        }
        return Result.success(orderInfo);
    }
}
